﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ThisIsFirstTest.Models.AccountModel;
using System.Web.Security;
using MealBooking.Core.Models.Accounts;
using MealBooking.Core;

namespace ThisIsFirstTest.Controllers.AccountController
{
    public class AccountController : Controller
    {
        #region account
        [Authorize]
        public ActionResult Index(string headerMessage = null)
        {
            var account = CoreService.AccountService.AccountDetail(new Account { Id = User.Identity.Name });
            ViewBag.Account = account;
            var customer = CoreService.AccountService.CustomerDetail(account.Id);
            ViewBag.Customer = customer;
            if (headerMessage == null)
            {
                ViewBag.HeaderTitle = "Welcome, " + account.Name;
            }
            else
            {
                ViewBag.HeaderTitle = headerMessage;
            }
            return View();
        }
        public ActionResult Detail(string id)
        {
            var account = CoreService.AccountService.AccountDetail(new Account { Id = id });
            ViewBag.Account = account;
            var customer = CoreService.AccountService.CustomerDetail(id);
            ViewBag.Customer = customer;
            return View();
        }
        public ActionResult LogOn(string headerMessage = null)
        {
            if (Request.IsAuthenticated)
            {
                return RedirectToAction("Index");
            }
            ViewBag.HeaderTitle = headerMessage + "Log On";
            return View();
        }
        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                ModelState.AddModelError("", "The user name or password provided is incorrect.");
                return View(model);
            }
            var account = CoreService.AccountService.ValidateUser(model.UserName, model.Password);
            if (account == null)
            {
                ModelState.AddModelError("", "The user name or password provided is incorrect.");
                return View(model);
            }
            FormsAuthentication.SetAuthCookie(account.Id, model.RememberMe);
            if (Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }
        [Authorize]
        public ActionResult ChangePassword()
        {
            return View();
        }
        [HttpPost]
        [Authorize]
        public ActionResult ChangePassword(ChangePasswordModel changePasswordModel)
        {
            if (!ModelState.IsValid)
            {
                return View(changePasswordModel);
            }
            string accountId = User.Identity.Name;
            bool result = CoreService.AccountService.ChangePassword(accountId, changePasswordModel.Password, changePasswordModel.NewPassword);
            if (!result)
            {
                ModelState.AddModelError("", "Password is incorrect.");
                return View(changePasswordModel);
            }
            Session.Clear();
            Session.Abandon();

            Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
            Response.Expires = 0;
            Response.Buffer = true;
            Response.ExpiresAbsolute = DateTime.Now.AddSeconds(-1);
            Response.AddHeader("pragma", "no-cache");
            Response.AddHeader("pragma", "no-store");
            Response.CacheControl = "no-cache";
            FormsAuthentication.SignOut();
            return RedirectToAction("LogOn", new { headerMessage = "change password success." });
        }
        [Authorize]
        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Index", "Home");
        }
        #endregion

        #region Register New Account
        public ActionResult Register()
        {
            ViewBag.HeaderTitle = "Register New User";
            return View();
        }
        [HttpPost]
        public ActionResult Register(RegisterNewAccountModel newAccountModel)
        {
            if (!ModelState.IsValid)
            {
                return View(newAccountModel);
            }
            var account = CoreService.AccountService.AccountDetail(new Account { Name = newAccountModel.UserName });
            if (account != null)
            {
                ModelState.AddModelError("Name", "User Name already Exists.");
                return View(newAccountModel);
            }
            account = new Account
            {
                Name = newAccountModel.UserName,
                Password = newAccountModel.Password,
                EmailAddress = newAccountModel.EmailAddress
            };
            account = CoreService.AccountService.RegisterNewAccount(account);
            if (account == null)
            {
                ModelState.AddModelError("", "Register Failed.");
                return View(newAccountModel);
            }
            return RedirectToAction("LogOn", new { headerMessage = "Register Success." });
        }
        #endregion

        #region Balance
        public ActionResult BalanceHistory(string id)
        {
            var customer = CoreService.AccountService.CustomerDetail(id);
            ViewBag.Customer = customer;
            var balanceHistories = CoreService.AccountService.BalanceHistory(id);
            return View(balanceHistories);
        }
        #endregion
    }
}
